<template>
  <div>
    <x-form ref="formRef" v-model:model="getProps.params" :rules="rules">
      <n-form-item label="落地页类型" path="default">
        <n-radio-group
          v-if="support_page_type_list"
          v-model:value="getProps.params.default"
          size="small"
          @update:value="onChangeType"
        >
          <n-radio-button v-for="item in support_page_type_list" :key="item.value" :value="item.page_type">{{
            item.description
          }}</n-radio-button>
        </n-radio-group>
      </n-form-item>
      <n-spin :show="materialLoading">
        <x-form v-if="canvas_page" ref="canvasFormRef" v-model:model="canvas_page" :rules="canvasRules">
          <n-form-item :label="canvas_page.description" path="default">
            <n-select
              v-model:value="canvas_page.default"
              :disabled="materialLoading"
              :options="canvasPageList"
              value-field="value"
              label-field="description"
              @update:value="onChangeCanvas"
            />
          </n-form-item>
        </x-form>
        <n-form-item v-if="material_replace" :label="material_replace.description">
          <n-checkbox-group v-model:value="checkMaterial" @update:value="onChangeMaterial">
            <n-checkbox
              v-for="item in material_replace.enum_property.enumeration"
              :key="item.name"
              :label="item.description"
              :value="item.name"
              :disabled="materialLoading"
            />
          </n-checkbox-group>
        </n-form-item>
      </n-spin>
      <!--行动按钮-->
      <TemplateRadio
        v-if="getProps.params.moment_action_button"
        :ref="getProps.params.moment_action_button.name"
        :key="getProps.params.moment_action_button.name"
        :params="getProps.params.moment_action_button"
        @switch="onSwitchActionButton"
      />
      <template v-if="isMomentAction">
        <n-form-item label="按钮文案" :show-require-mark="supportLinkNameTypeRequired">
          <!--按钮文案-->
          <n-select
            v-if="supportLinkNameType && supportLinkNameType.length > 0"
            v-model:value="checkPageType.support_link_name_type.default"
            :options="supportLinkNameType"
            value-field="link_name_type"
            label-field="description"
            @update:value="onChangeLinkNameType"
          />
        </n-form-item>
        <n-form-item label="跳转落地页" :show-require-mark="true">
          <!--落地页类型-->
          <n-radio-group
            v-if="supportLinkPageType && supportLinkPageType.length > 0"
            v-model:value="checkPageType.support_link_page_type.default"
          >
            <n-radio-button v-for="item in supportLinkPageType" :key="item.value" :value="item.link_page_type">{{
              item.description
            }}</n-radio-button>
          </n-radio-group>
        </n-form-item>
      </template>
    </x-form>
  </div>
</template>
<script setup lang="ts">
  import { useRoute } from 'vue-router'
  import { computed, onMounted, reactive, ref, watch } from 'vue'
  import { NFormItem, NRadioGroup, NRadioButton, NCheckboxGroup, NCheckbox, NSelect, NSpin, useMessage } from 'naive-ui'
  import { XForm } from '@/components'
  import TemplateRadio from '@/views/advertising/ads/create/components/step7/TemplateRadio.vue'
  import { useStore } from '@/store'

  const store = useStore()
  const route = useRoute()
  const emit = defineEmits(['change', 'changeMaterial', 'changeLinkNameType', 'actionChange'])
  const message = useMessage()
  const props = defineProps({
    params: {
      type: Object,
      default: () => ({})
    }
  })
  const isEdit = computed(() => {
    return store.state.intelligent.data.id
  })
  const creative = computed(() => {
    return store.state.intelligent.data.creative
  })
  const position = computed(() => {
    return store.state.intelligent.data.position
  })
  const accountCode = computed(() => {
    return store.state.intelligent.data.accountCode
  })
  const pageId = computed(() => {
    return store.state.intelligent.data.pageId
  })
  const getProps = reactive(props)
  const support_page_type_list = ref(getProps.params.support_page_type_list)
  const checkPageType = ref()
  const checkMaterial = ref([])
  const materialLoading = ref(false)
  const material_replace = ref()
  const canvas_page = ref()
  const canvasPageList = ref([])
  const momentActionButton = ref()
  const isMomentAction = ref(getProps.params.moment_action_button?.default)
  const supportLinkNameType = ref()
  const supportLinkNameTypeRequired = ref(false)
  const supportLinkPageType = ref()
  const formRef = ref()
  const canvasFormRef = ref()
  const rules = ref({
    default: {
      type: 'string',
      required: true,
      message: '请选择落地页类型',
      trigger: ['blur', 'change']
    }
  })
  const canvasRules = ref({
    default: {
      type: 'number',
      required: true,
      message: computed(() => (canvas_page.value ? `请选择${canvas_page.value.description}` : '请选择')),
      trigger: ['change']
    }
  })
  const count = ref(0)
  onMounted(() => {
    let listCount = 0
    support_page_type_list.value.forEach((item) => {
      if (item.page_type === getProps.params.default) {
        listCount++
      }
    })
    if (listCount === 0) {
      getProps.params.default = null
    }
    onChangeType(getProps.params.default)
    emit('changeMaterial', material_replace.value?.enum_property?.enumeration || [], checkMaterial.value)
    onChangeLinkNameType(checkPageType.value?.support_link_name_type?.default)
  })

  // 如果小程序页面改变，重新获取原生页
  watch(
    () => pageId.value,
    (val) => {
      // 先重置，在重新获取
      if (canvas_page.value) {
        canvas_page.value.default = null
      }
      getAdsCanvasPage()
    },
    { immediate: true }
  )

  // 选择落地页类型
  function onChangeType(value: any) {
    const find = support_page_type_list.value.find((item: { page_type: any }) => {
      return item.page_type === getProps.params.default
    })
    checkPageType.value = find
    // 选择的外部素材值
    checkMaterial.value =
      typeof getProps.params.material_replace_checked === 'string'
        ? [getProps.params.material_replace_checked]
        : getProps.params.material_replace_checked
    // 外部素材
    material_replace.value = find?.material_replace || null
    // 原生推广页
    canvas_page.value = find?.canvas_page || null
    // 按钮文案
    supportLinkNameType.value = find?.support_link_name_type?.list || []
    // 按钮文案必填项
    supportLinkNameTypeRequired.value = find?.support_link_name_type?.required
    // 落地页类型
    supportLinkPageType.value = find?.support_link_page_type?.list || []
    // 原生页，微信小程序切换后落地页类型默认值
    if (find?.page_type === 'PAGE_TYPE_MINI_PROGRAM_WECHAT') {
      if (checkPageType.value.support_link_page_type) {
        checkPageType.value.support_link_page_type.default = find?.support_link_page_type?.list[0]?.link_page_type
      }
    }
    // 如果有原生推广页
    if (find?.canvas_page) {
      getAdsCanvasPage()
      if (count.value > 0) {
        canvas_page.value.default = null
      }
      if (isEdit.value && canvas_page.value.default) {
        setTimeout(() => {
          onChangeCanvas()
        }, 2000)
      }
    }
    // 非原生推广页，视频重置为可选
    if (value !== 'PAGE_TYPE_CANVAS_WECHAT') {
      emit('change', [], null)
    }
    count.value++
  }
  function validate() {
    return new Promise((resolve, reject) => {
      if (getProps.params.default === 'PAGE_TYPE_CANVAS_WECHAT') {
        formRef.value?.validate(async (errors: any) => {
          if (!errors) {
            canvasFormRef.value?.validate(async (errors: any) => {
              if (!errors) {
                resolve(true)
              } else {
                resolve(false)
                console.log('errors', errors)
              }
            })
          } else {
            resolve(false)
            console.log('errors', errors)
          }
        })
      } else {
        formRef.value?.validate(async (errors: any) => {
          if (!errors) {
            resolve(true)
          } else {
            resolve(false)
            console.log('errors', errors)
          }
        })
      }
    })
  }
  function onChangeCanvas() {
    // console.log(canvas_page.value.default, canvasPageList.value, 'checkPage')
    const find = canvasPageList.value?.find((item: { value: any }) => {
      return item.value === canvas_page.value.default
    })
    emit('change', material_replace.value?.enum_property?.enumeration, find)
    // console.log(find, 'find')
  }
  // 选择媒体素材
  function onChangeMaterial(val, option) {
    if (option.actionType === 'check') {
      checkMaterial.value = [option.value]
    }
    // console.log(checkMaterial.value)
    // 清空素材数据
    if (canvas_page.value) {
      canvas_page.value.default = null
    }
    getAdsCanvasPage()
    emit('changeMaterial', material_replace.value.enum_property.enumeration, checkMaterial.value)
  }
  async function getAdsCanvasPage() {
    materialLoading.value = true
    if (creative.value.templateId && pageId.value) {
      await store
        .dispatch('intelligent/getAdsCanvasPage', {
          accountCode: accountCode.value,
          templateId: creative.value.templateId,
          siteSets: position.value.siteSet.join(','),
          overrideOption: checkMaterial.value ? checkMaterial.value[0] : null,
          refresh: 1,
          pageId: pageId.value
        })
        .then((res) => {
          const list = res.data.map((item: any) => {
            return {
              ...item,
              // description: item.description + `${item.appType !== 0 ? '(非和气小程序)' : ''}`,
              description: item.description,
              value: item.value,
              disabled: !item.can_use
            }
          })
          list.sort((a: any, b: any) => {
            return a.disabled - b.disabled
          })
          canvasPageList.value = list
          materialLoading.value = false
        })
        .catch(() => {
          materialLoading.value = false
        })
    }
    materialLoading.value = false
  }
  function onSwitchActionButton(val) {
    // console.log('行动按钮开关值=》', val, supportLinkNameType.value)
    if (!val) {
      isMomentAction.value = false
    } else {
      isMomentAction.value = true
    }
    emit('actionChange', val, supportLinkNameType.value)
  }
  function onChangeLinkNameType(val: any) {
    const find = supportLinkNameType.value.find(
      (item: any) => item.link_name_type === checkPageType.value.support_link_name_type?.default
    )
    // console.log(val, find, 2222222)
    emit('changeLinkNameType', val, find)
  }
  defineExpose({
    validate
  })
</script>

<style scoped lang="scss"></style>
